package com.yhd.admin.web.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yhd.admin.bean.Function;
import com.yhd.admin.service.FunctionService;
import com.yhd.admin.utils.EasyuiTreeNode;
import com.yhd.admin.utils.ServiceMessage;

@Controller
@RequestMapping("/function")
public class FunctionController {
	@Autowired
	private FunctionService functionService;
	
	@RequestMapping()
	public String showPage(){
		return "function";
	}
	
	//加载功能数据
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public @ResponseBody Object getList(@RequestParam(defaultValue="0")int id){
		List<Function> sons = functionService.getAsyncChildrenByPid(id);
		List<EasyuiTreeNode> nodes = new ArrayList<EasyuiTreeNode>();
		for(Function s : sons){
			EasyuiTreeNode node = ToEasyuiTreeNode(s);
			nodes.add(node);
		}
		return nodes;
	}
	
	private EasyuiTreeNode ToEasyuiTreeNode(Function f){
		EasyuiTreeNode node = new EasyuiTreeNode();
		node.setId(f.getId());
		node.setText(f.getName());
		//判断是否叶子节点
		if(f.getUrl()!=null){
			node.getAttributes().put("url", f.getUrl());
			node.setState("open");
		}
		return node;
	}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String functionAddPage(){
		return "function-add";
	}
	
	@RequestMapping("/name/check")
	public @ResponseBody ServiceMessage  functionNameCheck(Function function){
		Function f = functionService.checkFunctionName(function);
		return ServiceMessage.ok(f);
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public @ResponseBody ServiceMessage  addFunction(Function f){
		if(StringUtils.isEmpty(f.getUrl())){
			f.setUrl(null);
		}
		functionService.addFunction(f);
		return ServiceMessage.ok(f);
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String functionUpdatePage(@PathVariable int id,Model model){
		Function f  = functionService.getFunctionById(id);
		model.addAttribute("func", f);
		return "function-update";
	}
	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody ServiceMessage  updateFunction(Function f){
		if(StringUtils.isEmpty(f.getUrl())){
			f.setUrl(null);
		}
		functionService.updateFunction(f);
		return ServiceMessage.ok(f);
	}
	
	@RequestMapping("/delete")
	public @ResponseBody ServiceMessage  deleteFunction(int id){
		functionService.deleteFunctionById(id);
		return ServiceMessage.ok();
	}
}
